import json
import datetime as datetime1
from datetime import datetime
from django.utils import timezone


from django.db import transaction
from django.shortcuts import render

# Create your views here.
from django.views import View
from houses.models import House
from django import http

from orders.models import Order
from ihome.utils.response_code import RET

from users.models import User


class OrderHouseView(View):

    # def get(self,request):
    #     '''获取房源数据'''
    #     #获取租房ID,获取对应数据
    #     house_id = request.GET.get('hid')
    #     # house = request.GET
    #     house = House.objects.get(id=house_id)
    #     # house_id = house.get('id')
    #     title = house.title
    #     price = house.price
    #     image = house.index_image_url
    #     start_date = timezone.now()
    #     end_date = (start_date + datetime1.timedelta(days=1)).strftime('%Y-%m-%d')
    #     start_date = timezone.now().strftime('%Y-%m-%d')
    #     #拼接数据
    #     return http.JsonResponse({
    #         'data': {
    #             'house_id' : house_id,
    #             'title':title,
    #             'price':price,
    #             'img_url':image,
    #             'start_date':start_date,
    #             'end_date':end_date
    #         },
    #         'errno': '0',
    #         'errmsg': 'ok'
    #     })

    def get(self,request):
        # 判断房主还是用户　landlord or custom
        role = request.GET.get('role')
        user = request.user
        #1.根据landlord or custom ,确定返回订单
        if role == 'landlord':
            # orders = user.order_set.all().order_by('-create_time')
            orders = Order.objects.filter(house__user=user).order_by('-create_time')

        else:
            # orders = user.order_set.all().order_by('-create_time')
            orders = Order.objects.filter(user=user).order_by('-create_time')

        #2.遍历所有的订单
        order_data = []
        for order in orders:
            b = order.begin_date
            e = order.end_date
            c = order.create_time
            amount = order.amount
            comment = order.comment
            ctime = '%d-%02d-%02d  %02d:%02d' %(c.year,c.month,c.day,c.hour,c.minute)
            days = order.days
            end_date = '%d-%02d-%02d  %02d:%02d' %(e.year,e.month,e.day,e.hour,e.minute)
            img_url = order.house.index_image_url
            order_id = order.id
            start_date = '%d-%02d-%02d  %02d:%02d' %(b.year,b.month,b.day,b.hour,b.minute)
            status = order.status
            title= order.house.title


            context = {
                'amount':amount,
                'comment':comment,
                'ctime':ctime,
                'days':days,
                'end_date':end_date,
                'img_url':img_url,
                'order_id':order_id,
                'start_date':start_date,
                'status':status,
                'title':title
            }

            order_data.append(context)

        return http.JsonResponse({
            'data':{
                'orders':order_data
            },
            'errmsg':'OK',
            'errno':'0'
        })

    def post(self,request):
        '''新增订单数据'''
        #整体检验
        #检验时间是否正常
        #检验数据库中是否有对应的房屋记录

        order_dict = json.loads(request.body.decode())
        # order_id = order_dict.get('order_id')
        house_id = order_dict.get('house_id')

        start_date_str = order_dict.get('start_date')
        end_date_str = order_dict.get('end_date')
        if not all([house_id,start_date_str,end_date_str]):
            return http.HttpResponseForbidden('数据不全')
        start_date = datetime.strptime(start_date_str,'%Y-%m-%d')
        end_date = datetime.strptime(end_date_str,'%Y-%m-%d')
        if end_date < start_date:
            return http.HttpResponseForbidden('时间数据不对')
        # try:
        #     house = House.objects.get(id = house_id)
        # except Exception as e:
        #     return http.HttpResponseForbidden('没有对应房屋数据')
        price = House.objects.get(id=house_id).price
        #保存数据（事务）
        with transaction.atomic():
            day =end_date - start_date
            days = day.days
            user = request.user
            #设置回滚点
            save_id = transaction.savepoint()
            try:
                order = Order.objects.create(
                    user = user,
                    house = House.objects.get(id=house_id),
                    begin_date = start_date,
                    end_date = end_date,
                    days = days,
                    house_price = price,
                    amount = days * price,
                )
            except Exception as e:
                transaction.savepoint_rollback(save_id)
                return http.JsonResponse({
                    'code':RET.DBERR,
                    'errmsg':'增加订单出错'
                })
            transaction.savepoint_commit(save_id)
            #获取刚新增的订单ID
            order_id = len(Order.objects.all())
        return http.JsonResponse({
            'data':{
              'order_id': order_id
            },
            'errno':'0',
            'errmsg':'ok'
        })

    def put(self,request):
        request_dict = json.loads(request.body.decode())
        # user_id = request_dict.get('user_id')
        order_id = request_dict.get('order_id')
        action = request_dict.get('action')
        reason = request_dict.get('reason')
        user = request.user
        try:
            order = Order.objects.get(id=order_id)
        except Exception as e:
            return http.HttpResponseForbidden('数据不全')

        # try:
        #     order = Order.objects.get(id=order_id)
        #     user_id1 = order.User_set.get('user_id')
        # except User.DoesNotExist:
        #     return http.HttpResponseForbidden('用户或订单数据不存在')
        # if user_id != user_id1:
        #     return http.HttpResponseForbidden('用户或订单数据不存在')
        #接单
        if action == 'accept':
            #将订单状态修改为待支付
            status = "WAIT_PAYMENT"
            order.status = status
            order.save()
        #拒单
        else:
            #将订单状态修改为已拒单
            status = 'REJECTED'
            order.status = status
            order.comment = reason
            order.save()

        return http.JsonResponse({
            'errno':'0',
            'errmsg':'ok'
        })


class OrdersCommentView(View):
    """评价订单"""

    def put(self, request):
        req_data = json.loads(request.body.decode())
        order_id = req_data['order_id']
        comment = req_data['comment']
        order = Order.objects.filter(id=order_id)
        order.update(status='COMPLETE', comment=comment)

        return http.JsonResponse({
            'errno':'0',
            'errmsg':'OK'

        })